<?php
/**
 +--------------------------------
 * SalesAction.class.php （产品促销活动：聚划算，团购，秒拍，大宗批发）
 * date:2013.09.17
 * @author tanbin
 +--------------------------------
 *
 */
class SalesAction extends BaseAction {
	protected $prodes, $product ,$_platform;
	protected $ProductCoupon, $ProductPackage;
	function _initialize() {
		parent::_initialize ();		
		import ( 'Com.Product' );
		$this->product = new Product ();
		
		$this->ProductCoupon = M("ProductCoupon");
		$this->ProductPackage = M("ProductPackage");
		
		$this->_platform = 'SMW01';
	}
	
	
	/**
	 * 商品优惠列表 （优惠券、巨划算）
	 */
	function index(){
		$where = array();
		$listkey = $_REQUEST['listkey'];
		if($listkey == 'coupon'){ //产品优惠券
			$where['type'] = 'USE';
		}elseif($listkey == 'ju'){
			$where['type'] = 'SALE';
		}
		if(!empty($_REQUEST['proid'])){
			$where['product_id'] = $_REQUEST['proid'];
		}		
		$where=parent::create_where($where);
			
		//$map['name'] = array('neq','');
		//获取产品优惠信息。
		$model = M('ProductCoupon');
		$count = $model->join(' as pc left join product as p on pc.product_id = p.id')->where($where)->count();
		$page=new Page($count,$this->listrows);
		$offset = $page -> firstRow;
		$length = $page -> listRows;
	
	
		$res = $model->field("pc.* , image , name")
		->join(' as pc left join product as p on pc.product_id = p.id')
		//->join(' product_description as pd on pc.product_id = pd.product_id')
		->where($where)->order($this->order)->limit($offset,$length)->select();
	
		//处理和更新聚划算数据。
		foreach ($res as $key => $vo){
			if($vo['status'] == 1){
				$enable = $this->checktime($vo['starttime'], $vo['endtime']);
				if(empty($enable)){
					$res[$key]['status'] = 0;
					//执行更新数据库操作
					$this->status($vo['id'],0);
				}
			}
		}
	
		//	dump($res);echo $model->getLastSql();
		//$pro_coupon = $this->product_coupon($proid,'SALE');
	
		$this->assign("totalCount",$count);
		$this->assign('listkey',$listkey);
		$this->assign("list",$res);
		$this->display();
	}
	
	
	
	/**
	 * 聚划算添加
	 */
	function edit(){
		$id = $_GET['id'];
		$proid = $_GET['proid'];
		if(!$proid){
			$this->_ajm(300,'数据不存在！',0);
		}
		//获取商品名称、主图、价格信息
		$res = $this->product->_description($proid);
		$product['name'] = $res['name'];
		$res = $this->product->product($proid,'image');
		$product['image'] = $res['image'];
		$product['price'] = $this->product->_price_b2b($proid);
	
		if($id){
			//有id 的情况，直接获取信息。跳转到编辑页面
			$map['id'] = $id;
			$map['status'] = 1;
			$procoupon = $this->ProductCoupon->where($map)->find();
		}else{
			// 没有id 的情况，获取该商品的聚划算信息。（数据库同一商品只存在 一条状态为 1 的聚划算信息。）
			$map = array();
			$map['product_id'] = $proid;
			$map['type'] = 'SALE';
			$map['status'] = 1;
			//获取该商品，状态为1 的聚划算信息。
			$procoupon = $this->ProductCoupon->where($map)->find();
			//此商品，状态为1的数据存在
			if($procoupon){
				//判断是否过期
				$enable = $this->checktime($procoupon['starttime'], $procoupon['endtime']);
				$procoupon['enable'] = $enable;
				//如果已经过期，更新状态。并且清空 $procoupon(恢复新增状态) ，否则是 “编辑状态”
				if(empty($enable)){
					$this->status($procoupon['id'],0);
					$procoupon = array();
				}
			}
		}
		//print_r($procoupon);exit;
		$this->assign('listkey',$_REQUEST['listkey']);
		$this->assign('product',$product);
		$this->assign("procoupon",$procoupon);
		$this->assign('proid',$proid);
		$this->display();
	}
	
	

	/**
	 * 聚划算数据更新
	 */
	function save(){
		$request = $_POST['data'];
		$request['value'] = $request['value']*100;
		//判断商品是否在同时间被下架
		$info = $this->product->product($request['product_id'],'status',1);
		$prostatus = $info['status'];
		if(!$prostatus){
			$this->_ajm(300,'保存数据失败，商品已被下架',1);
			return false;
		}
	
		$data = array();
		$data['platform'] = $this->_platform;
		if($_REQUEST['listkey'] == 'ju'){
			$data['type'] = 'SALE';
		}elseif($_REQUEST['listkey'] == 'coupon'){
			$data['type'] = 'USE';
		}
		foreach ($request as $key=>$value){
			if(!empty($request[$key]) || $key=='number'){
				$data[$key] = $value;
			}
		}
		if($data['starttime']){
			$data['starttime'] = gettime($request['starttime']);
		}
		if($data['endtime']){
			$data['endtime'] = gettime($request['endtime']);
		}
		//print_r($request);print_r($data); echo date('Y-m-d H:i:s',"1392637500");exit();
		if($request['id']){
			$reid = $this->ProductCoupon->save($data);
		}else{
			$reid = $this->ProductCoupon->add($data);
		}
		if($reid || $reid===0){
			$this->_ajm(200, '修改成功！');
		}else{
			$this->_ajm(300,'保存数据失败，请重试',0);
			$this->display();
		}
	}
	
	
	
	/**
	 *更改优惠活动状态
	 *@date 2013-10-16
	 *@time 上午11；29
	 *@param $id : product_coupon表中的主键
	 *@param $status:更新的状态
	 */
	function status($id , $status = 0){
		$model = M("ProductCoupon");
		$map['id'] = $id;
		$data['status'] = $status;
		$reid = $model->where($map)->save($data);
		return $reid;
	}
	
	
	/**
	 * 优惠活动算数据删除
	 */
	function delete(){
		$ids = empty($_GET['id']) ? $_REQUEST['ids'] : $_GET['id'];
		$product_id = $_GET['proid'];
		if(!$ids) $this->_ajm(300,'此数据不存在！',0);
		
		$where['id'] = 	is_array($ids) ? array('in',implode(',',$ids)) : $ids;
		$reid = $this->ProductCoupon->where($where)->delete();
			
		if($reid){
			$this->_ajm(200, '删除成功！', 1);
		}else{
			$this->_ajm(300,'保存数据失败，请重试',0);
		}
		$this->display();
	}
	
	
	/**
	 * 结束优惠活动
	 * @author tb
	 * @date 2013.12.25
	 */
	function over(){
		$id = $_GET['id'] ;
		if(!$id){
			$this->_ajm(300,'选择数据错误！');
		}
		$reid = $this->status($id);
		if(intval($reid)>=0){
			$this->_ajm(200, '操作成功！', 1);
		}else{
			$this->_ajm(300,'操作失败，请重试',0);
		}
	}
	

	/**
	 * 套餐列表
	 */
	function package_index(){
		$where = array();
		$selproid = $_REQUEST['selproid'];
		if($_REQUEST['type']){
			$where['type'] = $_REQUEST['type'];
		}
		
		$where=parent::create_where($where);		
				
		$count = $this->ProductPackage->where($where)->count();
		$page = new Page($count,$this->listrows);
		$offset = $page -> firstRow;
		$length = $page -> listRows;		
		$res = $this->ProductPackage->where($where)->limit($offset,$length)->select();
		$this->assign('type',$where['type']);
		$this->assign("keywords",$this->keywords);
		$this->assign('selproid',$selproid);
		$this->assign("totalCount",$count);
		$this->assign('list',$res);
		$this->display();
	}
	
	
	/**
	 * 添加套餐
	 */
	function package_edit(){
		$id = $_REQUEST['id'];
		$proid = $_REQUEST['proid'];
		if($proid){
			$product = $this->product->oneproinfo( $proid );
			$this->assign('product',$product);
		}
		
		$type = $_REQUEST['type'];
		if($id){
			$res = $this->ProductPackage->find($id);
			$this->assign('package',$res);
		}
		$this->assign('proid',$proid);
		$this->assign('type',$type);
		$this->display();
	}
	
	
	/**
	 * 套餐信息保存
	 */
	function package_save(){
		$request = $_POST['data'];
		$request['all_special_price'] = $request['all_special_price']*100;
		foreach ($request as $key=>$value){
			if(!empty($request[$key])){
				$value = trim($value);
				if($key == 'start_time' || $key == 'end_time'){
					$value = strtotime($value);
				}
				$data[$key] = $value;
			}
		}
		
		//处理商品价格
		
		
		if($request['id']){
			$reid = $this->ProductPackage->save($data);
		}else{
			$reid = $this->ProductPackage->add($data);
		}
		if($reid){
			$this->_ajm(200, '添加成功！', 0);
		}else{
			$this->_ajm(300,'保存数据失败，请重试',0);
		}
		$this->display();
	}
	
	
	/**
	 * 套餐删除
	 */
	function package_del(){
		$id = $_GET['id'];		
		if(!$id) $this->_ajm(300,'此数据不存在！',0);
			
		$reid = $this->ProductPackage->delete($id);

		if($reid){
			$this->_ajm(200, '删除成功！', 1, U('Sales/package_index',array('id'=>$product_id)));
		}else{
			$this->_ajm(300,'保存数据失败，请重试',0);
		}
		$this->display();
	}
	
	/**
	 * 添加产品到套餐选择页面
	 */
	function package_select(){
		$product_id = $_GET['id'];
		$type = empty($_REQUEST['type']) ? 'BIG' : $_REQUEST['type'];
		$map['type'] = $type;
		//大宗批发只允许一件商品的情况。
		if($map['type'] == 'BIG'){
			$map['product_ids'] = '';
		}
		$ajax = $_REQUEST['ajax'];
		//获取所有的套餐信息
		$res = $this->ProductPackage->field('id,title,type')->where($map)->select();
		
		if($ajax == 1){
			$this->ajaxReturn($res);
		}else{
			$this->assign('type',$type);
			$this->assign('seleclist',$res);
			$this->assign('proid',$product_id);
			$this->display();
		}
	}
	
	/**
	 * 添加产品到套餐
	 */
	function package_addproduct(){
		$product_id = $_REQUEST['proid'];
		$package_id = $_REQUEST['id'];
		if(!$product_id || !$package_id){
			$this->_ajm(300,'系统读取商品失败!',0);
		}
		$res = $this->ProductPackage->find($package_id);
		if($res){
			//判断是否已经添加了此产品
			$proids = $res['product_ids'];
			$idsarr = explode(',', $proids);
			if(in_array($product_id, $idsarr)){
				$this->_ajm(200, '添加成功！', 0,'','dialogp');
			}
					
			$data['id'] = $package_id;
			$data['product_ids'] = empty($res['product_ids']) ? $product_id : $res['product_ids'].','.$product_id;
			$proprice = $this->product->_price_b2b($product_id);
			$jiayi = $product_id.'|'.$proprice['jiayi'];
			$data['special_price'] = empty($res['special_price']) ? $jiayi : $res['special_price'].','.$jiayi;
			$reid = $this->ProductPackage->save($data);
			if($reid){
				$this->_ajm(200, '添加成功！', 0);
			}else{
				$this->_ajm(300,'保存数据失败，请重试',0);
			}
		}
		
	}
	

	/**
	 * 套餐产品列表
	 */
	function package_pro_index(){
		$id = $_GET['id'];
		if($id){
			$res = $this->ProductPackage->find($id);
			if($res['product_ids']){
				$proids = $res['product_ids'];
				$proid_arr = explode(',',$proids);
				$list = array();
				foreach ($proid_arr as $pid){
					$vo = $this->product->description($pid,'product_id,name');
					$list[$pid]['product_id'] = $pid;
					$list[$pid]['name'] = $vo[0]['name'];
					$vo = $this->product->_price_b2b($pid); 
					$list[$pid]['jiayi'] = $vo['jiayi'];
				}
			}
		}
		$this->assign('package',$res);
		$this->assign('list',$list);
		$this->display();
	}
	
	/**
	 * 套餐移除产品
	 */
	function package_pro_del(){
		$id = $_GET['id'];
		//$id = 2;
		$product_id = $_GET['proid'];
		//$product_id = 22;
		$type = $_GET['type'];
		//$type = 'BIG';
		$data['id'] = $id;
		if($type == 'BIG'){
			$data['product_ids'] = '';
			
		}else{
			$res = $this->ProductPackage->find($id);
			$prostr = $res['product_ids'];
			$proid_arr = explode(',', $prostr);
			foreach ($proid_arr as $key=>$pid){
				if($pid == $product_id){
					unset($proid_arr[$key]);
					break;
				}
			}
			$data['product_ids'] = implode(',', $proid_arr);
		}
	
		$reid = $this->ProductPackage->save($data);
		if($reid){
			$this->_ajm(200, '移除成功！', 0);
		}else{
			$this->_ajm(300,'移除失败，请重试',0);
		}
	}
	
	/**
	 * 产品优惠券（添加）
	 * */
	function procoupon_edit(){
		if ( $_REQUEST['todo'] == 'addcoupon' ) {
			$this->assign("ids",$_REQUEST['ids']);
			$this->assign("todo",$_REQUEST['ftodo']);
			$this->display();
		} elseif ( ($_REQUEST['todo'] == 'insert')) {
			$data = $_REQUEST['data'];
			$data['value'] = $data['value'] * 100;
			$data['subject'] = 'CV';
			$data['platform'] = 'SMW01';
			$data['status'] = 1;
			$data['type'] = 'USE';
			$tem = array();
			$ids = explode(',',$_REQUEST['ids']);
			$dao = M('product_coupon');	
			foreach ($ids as $id){
				$data['product_id'] = $id;
				$res = $dao->add($data);
				$tem[] = $dao->getLastSql();
			}
			die( json_encode( $tem ) );
		}else{
			$re['ids'] = implode(',',$_REQUEST['ids']);
			$re['ftodo'] = $_REQUEST['ftodo'];
			$re['action'] = 'procoupon_edit';
			die( json_encode( $re ) );
			//$this->display();
		}
	}
	
	/**
	 * 产品优惠券保存
	 * */
	function procoupon_save(){
		$data = $_REQUEST['data'];
		$data['value'] = $data['value'] * 100;
		$data['subject'] = $where['subject'] = 'CV';
		$data['platform'] = 'SMW01';
		$data['status'] = $where['status'] = 1;
		$data['type'] = $where['type'] = 'USE';	
		$ids = explode(',',$_REQUEST['proids']);
		$dao = M('product_coupon');
		foreach ($ids as $id){			
			$data['product_id'] = $where['product_id'] = $id;
			$info = $dao->where($where)->find();
			if(empty($info)){
				$res = $dao->add($data);
				if(!$res){
					$item .= $id.'&nbsp;&nbsp;';
				}
			}
		}
		if($item){
			$this->_ajm(300,'产品id为：'.$item.'没有添加优惠券，请把此错误截图提交给技术部，进行处理！');
		}else {
			$this->_ajm(200,'保存成功');
		}
	}
	
	
}

